<?php

namespace app\home\controller;

use app\home\model\UserOrder;
use app\home\service\NotifyService;
use app\home\service\OrderService;
use think\Request;

class Pay800034 extends BasePay
{

    const CLIENT_ID = 110954515; //就是appid 和 appsecret
    const CLIENT_SECRET = 'bef704ec69744d7c62263b62e03867870babe7d9fac98bb30e91ad9b3c5a16ae';
    

    public function test(){
        $Huawei = new \app\home\service\Huawei(self::CLIENT_ID,self::CLIENT_SECRET);
        $res = $Huawei->get_token();
        var_dump($res);die;
    }


    public function order()
    {
        parent::order();

        $data_Arr['code'] = 'success';

        $return['requestId'] = $this->order_array['id'];
        // 华为的配置为字母a+计费点 如a1000 a3000（看具体配置）
        $return['ProductId'] = $this->order_array['goods_id'];
        $return['amount'] = $this->order_array['amount']*100;

        $data_Arr['data'] = $return;

        putsuccess($data_Arr);

    }

    public function notify()
    {
        parent::notify();
        $params = Request::instance()->param();
        mylog($params);
        try{

            $Huawei = new \app\home\service\Huawei(self::CLIENT_ID,self::CLIENT_SECRET);

            // 华为接口验证订单
            $res = $Huawei->verify_order($params["token"],$params["productId"]);
            $data = json_decode($res,true);
            if(empty($res) || empty($data['purchaseTokenData'])){
                throw new \Exception('purchaseState empty');
            }
            $purchaseTokenData = json_decode($data['purchaseTokenData'],true);
            $order_amount = explode('=',$purchaseTokenData['developerPayload']);
            if($purchaseTokenData['purchaseState'] != 0){
                throw new \Exception('purchaseState false');
            }

            $notifyService = new NotifyService();
            $order_info = $notifyService->checkOrder($order_amount[0],$order_amount[1]/100);
            if($order_info == false){
                throw new \Exception('checkOrder false');
            }
            // 状态已经处理的订单直接返回成功
            if ($order_info["status"] == OrderService::PAY_STATUS_PAID) {
                mylog("订单已经处理过了");
                return "success";
            }

            //保存第三方单号
            $tradeLog = (new \app\home\model\TradeLog)->where(['id' =>$order_amount[0]])->find();
            if ($tradeLog) {
                $tradeLog->transactionID = $purchaseTokenData['orderId'];
                $tradeLog->save();
            }
            

            // 发货
            if($notifyService->notifyProcess($order_info) == false){
                throw new \Exception('notifyProcess false');
            }

            // 通知华为确认购买
            $Huawei->confirm_order($params["token"],$params["productId"]);

            return "success";
        }catch(\Exception $exception){
            mylog('Pay800034-error:'.$exception->getMessage().' line:'.$exception->getLine().' file:'.$exception->getFile());
            return "error";
        }
    }
}
